import subprocess
import sys

from PyQt5.QtCore import QThread, pyqtSignal, Qt

from resources.mainwindow import Ui_MainWindow
from PyQt5.QtWidgets import QMainWindow, QMessageBox, QFileDialog, QTableWidgetItem, QHeaderView, QAbstractItemView
import os
from PyQt5 import QtCore, QtGui, QtWidgets
from core.PDF import PDF


class ProcessFlowWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.initUi()
        self.source_dir_path = None
        self.process_thread = None

    def initUi(self):
        self.selectButton.clicked.connect(self.select_resource_file)
        self.startButton.clicked.connect(self.start_process)
        self.openButton.clicked.connect(self.open_dir)
        self.progressBar.setValue(0)
        self.progressBar.update()

    def select_resource_file(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        directory = QFileDialog.getExistingDirectory(self, "选择文件夹",
                                                     os.path.join(os.path.expanduser('~'), "Desktop"),
                                                     options=options)
        if directory:
            print(f"Selected directory: {directory}")
            self.dirPath.setText(directory)
            self.dirPath.setText(directory)

    def start_process(self):
        self.source_dir_path = self.dirPath.text()
        self.process_thread = ExcelProcessThread(self.source_dir_path)
        self.process_thread.progress_signal.connect(self.progress_callback)
        self.process_thread.exception_signal.connect(self.show_message)
        self.process_thread.start()

    def progress_callback(self, value):
        self.progressBar.setValue(int(float(value)))
        self.progressBar.update()

    def show_message(self, error_str):
        QtWidgets.QMessageBox.critical(self, "Error", error_str)

    def open_dir(self):
        if sys.platform == 'darwin':  # macOS
            subprocess.Popen(['open', '--', self.source_dir_path])
        elif sys.platform == 'win32':  # Windows
            subprocess.Popen(['explorer', self.source_dir_path])
        else:
            # 如果需要，处理其他平台
            # 使用 subprocess.Popen() 打开文件夹（针对GNOME桌面环境）
            subprocess.Popen(['nautilus', self.source_dir_path])

    def keyPressEvent(self, event):
        # 检测按键是否为Command + W
        if event.key() == Qt.Key_W and event.modifiers() == Qt.ControlModifier:
            # 在macOS上，ControlModifier对应Command键
            # 调用close方法来关闭窗口
            self.queryExit()
        else:
            # 对于其他按键事件，可以调用基类的keyPressEvent
            super().keyPressEvent(event)

    def queryExit(self):
        res = QtWidgets.QMessageBox.question(self, "Warning", "Quit?",
                                             QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel)
        if res == QtWidgets.QMessageBox.Yes:
            QtCore.QCoreApplication.instance().exit()

class ExcelProcessThread(QThread):
    progress_signal = pyqtSignal(int)
    exception_signal = pyqtSignal(str)

    def __init__(self, source_dir_path):
        super().__init__()
        self.source_dir_path = source_dir_path
        self.excel_process = None

    def run(self):
        try:
            pdf = PDF(self.source_dir_path)
            self.progress_signal.emit(0)
            pdf.parse_excel_file()
            self.progress_signal.emit(10)
            pdf.pdf_add_pic()
            self.progress_signal.emit(20)
            pdf.parse_image_dir()
            self.progress_signal.emit(30)
            pdf.pdf_add_text()
            self.progress_signal.emit(40)
            pdf.pdf_add_DL_cir()
            self.progress_signal.emit(50)
            pdf.pdf_add_QPL_rect()
            self.progress_signal.emit(60)
            pdf.pdf_add_arrow()
            self.progress_signal.emit(70)
            pdf.pad_add_out_rect()
            self.progress_signal.emit(80)
            pdf.pdf_add_others()
            self.progress_signal.emit(90)
            pdf.pdf_add_border()
            self.progress_signal.emit(95)
            pdf.pdf_save()
            self.progress_signal.emit(100)
        except Exception as e:
            self.exception_signal.emit(str(e))
